package com.cuitrip.business.home.my;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.bill.BillActivity;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.home.my.card.PromotionActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.proxy.LoginProxy;
import com.cuitrip.business.notice.MessageListActivity;
import com.cuitrip.business.setting.SettingActivity;
import com.cuitrip.business.tripservice.CreateTripGuideActivity;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.user.CertActivity;
import com.cuitrip.business.user.EditSelfInfoActivity;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.proxy.UserInfoProxy;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.resource.DrawableClass;
import com.cuitrip.resource.ResourceManager;
import com.cuitrip.service.R;
import com.cuitrip.util.PlatformUtil;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.network.proxy.ApiProxyBuilder;
import com.lab.network.proxy.ApiProxyCallBack;
import com.lab.network.util.NetworkUtil;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.ArrayUtil;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MyPageFragment extends CustomUiFragment {
    public static final String TAG = "MyPageFragment";
    public static final int REQUEST_FOR_EDIT = 1002;
    private static final int REQUEST_CODE_EDIT_SELF_INFO = 1001;

    @Bind(R.id.cert_layout)
    ItemLayout mCertLayout;

    @Bind(R.id.card_layout)
    ItemLayout mCardLayout;

    @Bind(R.id.verifiedView)
    ImageView vertifiedView;

    @Bind(R.id.setting_layout)
    ItemLayout mSettingLayout;

    @Bind(R.id.bill_layout)
    ItemLayout mBillLayout;

    @Bind(R.id.role_layout)
    ItemLayout mRoleLayout;

    @Bind(R.id.messageLayout)
    ItemLayout messageLayout;

    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_job)
    TextView userJob;
    @Bind(R.id.user_verify_info)
    TextView userVerifyInfo;
    @Bind(R.id.my_layout)
    RelativeLayout myLayout;
    @Bind(R.id.author_img)
    ImageView mImage;


    private ApiProxy apiProxy;
    private IProxyCallback callBack = new ApiProxyCallBack<CtUserInfo>() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(CtUserInfo userInfo, CtApiResponse response) {
            if (!isAdded()){
                return false;
            }
            if (userInfo != null) {
                CtUserInfo info = LoginInstance.updateProfile(AppCoreRuntime.context, userInfo, false);
                if (info == null) {
                    return super.onSuccess(userInfo, response);
                }
                if (LoginInstance.getInstance().getUserInfo() != null) {
                    LoginInstance.getInstance().getUserInfo().setHasUnReadMsg(userInfo.getHasUnReadMsg());
                }
                updateUnReadView(userInfo.getUnReadMsgNum());
            }
            return super.onSuccess(userInfo, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            if (!isAdded()){
                return false;
            }
            String msg;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                msg = response.msg;
            } else {
                msg = PlatformUtil.getInstance().getString(R.string.feedback_data_err);
            }
            MessageUtils.showToast(msg);
            return super.onFaild(response);
        }
    };
    private IProxyCallback callBackChangeType = new ApiProxyCallBack() {
        @Override
        public void doPreWork(CtApiResponse response) {
            hideLoading();
        }

        @Override
        public boolean onSuccess(Object data, CtApiResponse response) {

            CtUserInfo info = LoginInstance.getInstance().getUserInfo();
            int type = info.isTravel() ? CtUserInfo.USER_FINDER : CtUserInfo.USER_TRAVEL;
            info.setType(type);
            Intent intent = new Intent(getActivity(), IndexActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            if (!info.isTravel() && isShow) {
                startActivity(new Intent(getActivity(), CreateTripGuideActivity.class));
            }
            LoginInstance.updateProfile(AppCoreRuntime.context, info, true);
            return super.onSuccess(data, response);
        }

        @Override
        public boolean onFaild(CtApiResponse response) {
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                ToastUtil.toast(response.msg);
            }
            return super.onFaild(response);
        }
    };

    private boolean isShow = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        apiProxy = ApiProxyBuilder.getBuilder().addApiCallBack(ApiManager.GET_USER_INFO, callBack)
                .addApiCallBack(ApiManager.CHANGE_TYPE, callBackChangeType).build();
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.ct_my);
    }


    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
    }

    @Override
    public void initListener() {
        super.initListener();
    }

    public void onResume() {
        super.onResume();
        TrackUtil.trackScreenName("/user");
        if (LoginInstance.isLogin()) {
            requestUserInfo(LoginInstance.getInstance().getUserInfo().getUid());
        }
        refreshView();
    }

    private void refreshView() {
        updateRoleLayout();
        myLayout.setBackgroundColor(ResourceUtil.getThemeColor());
        userJob.setVisibility(LoginInstance.isLogin() ? View.VISIBLE : View.GONE);
        userVerifyInfo.setVisibility(LoginInstance.isLogin() ? View.VISIBLE : View.GONE);
        if (!LoginInstance.isLogin()) {
            userName.setText(R.string.sign_in_not);
            return;
        }
        CtUserInfo info = LoginInstance.getInstance().getUserInfo();
        ImageHelper.displayPersonImage(info.getHeadPic(), mImage, null);
        userName.setText(info.getNick());
        userJob.setText(info.getCareer());
        SpannableStringBuilder stringBuilder = UserInfoProxy.getInstance().getFullBindBuilder(info);
        stringBuilder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.ct_white)),0,stringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        stringBuilder.setSpan(new AbsoluteSizeSpan(16,true),0,stringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        userVerifyInfo.setText(stringBuilder);
        updateUnReadView(info.getUnReadMsgNum());
    }

    private void updateRoleLayout() {
        if (!LoginInstance.isLogin()) {
            mBillLayout.setVisibility(View.GONE);
            mCardLayout.setVisibility(View.VISIBLE);
            mRoleLayout.setVisibility(View.GONE);
            vertifiedView.setVisibility(View.GONE);
            return;
        }
        if (LoginInstance.getInstance().getUserInfo().isIdentityValidated()) {
            vertifiedView.setVisibility(View.VISIBLE);
            vertifiedView.setImageDrawable(ResourceManager.getDrawable(DrawableClass.VeritifiedSmallDrawable));
        } else {
            vertifiedView.setVisibility(View.INVISIBLE);
        }
        if (LoginInstance.getInstance().getUserInfo().isTravel()) {
            mBillLayout.setVisibility(View.GONE);
            mCardLayout.setVisibility(View.VISIBLE);
            mRoleLayout.setVisibility(View.VISIBLE);
            mRoleLayout.setleftText(getString(R.string.user_swtich_to_insider));
        } else {
            mBillLayout.setVisibility(View.VISIBLE);
            mCardLayout.setVisibility(View.GONE);
            ;
            mRoleLayout.setVisibility(View.VISIBLE);
            mRoleLayout.setleftText(getString(R.string.user_swtich_to_traveler));
        }
    }

    private void updateUnReadView(int unReadMsgNum) {
        TextView textView = messageLayout.getmRightTextView();
        textView.setBackgroundResource(R.drawable.message_background);
        textView.setTextColor(ResourceUtil.getColor(R.color.ct_white));
        textView.setTextSize(12);
        ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        textView.setLayoutParams(layoutParams);
        textView.setGravity(Gravity.CENTER);
        textView.setPadding(Utils.dp2pixel(4),Utils.dp2pixel(1),Utils.dp2pixel(4),Utils.dp2pixel(1));
        if (unReadMsgNum<1){
            textView.setVisibility(View.INVISIBLE);
        }else{
            textView.setVisibility(View.VISIBLE);
            textView.setText(String.valueOf(unReadMsgNum));
        }
    }

    private void requestUserInfo(String uid) {
        UserBusiness.getUserInfo(apiProxy, uid);
    }


    public void initData() {
        if (LoginInstance.isLogin()) {
            ServiceBusiness.getServiceList(new ApiProxy(new IProxyCallback() {
                @Override
                public boolean onProxyResult(ProxyResult<?> result) {
                    CtApiResponse response = (CtApiResponse) result.getData();
                    if (response != null && response.code == CtResponseCode.RESULT_OK) {
                        if (response.result instanceof List) {
                            List<ServiceInfo> serviceInfos = (List<ServiceInfo>) response.result;
                            isShow = ArrayUtil.isNullOrEmpty(serviceInfos) ? true : false;

                        }

                    }
                    return false;
                }
            }));
        }
    }

    @OnClick(R.id.my_layout)
    void gotoSelfPage() {
        if (LoginInstance.isLogin()) {
            TrackUtil.trackScreenName("/user/about/edit");
            startActivityForResult(new Intent(getHostActivity(), EditSelfInfoActivity.class), REQUEST_CODE_EDIT_SELF_INFO);
        } else {
            LoginProxy.getInstance().gotoUserEnter(getActivity());
        }
    }

    @OnClick(R.id.bill_layout)
    void gotoBillPage() {
        if (LoginInstance.isLogin()) {
            TrackUtil.trackScreenName("/insider/transactions");
            BillActivity.start(getActivity());
        } else {
            LoginProxy.getInstance().gotoUserEnter(getActivity());
        }
    }

    @OnClick(R.id.card_layout)
    void gotoCardPage() {
        if (LoginInstance.isLogin()) {
            TrackUtil.trackScreenName("/user/coupon");
            //CardActivity.startActivity(getActivity());
            PromotionActivity.startActivity(getActivity(),false);
        } else {
            LoginProxy.getInstance().gotoUserEnter(getActivity());
        }
    }

    @OnClick(R.id.cert_layout)
    void gotoCert() {
        if (LoginInstance.isLogin()) {
            startActivity(new Intent(getActivity(), CertActivity.class));
            TrackUtil.trackScreenName("/user/verification");
        } else {
            LoginProxy.getInstance().gotoUserEnter(getActivity());
        }
    }

    @OnClick(R.id.setting_layout)
    void gotoSetting() {
        TrackUtil.trackScreenName("/settings");
        startActivity(new Intent(getActivity(), SettingActivity.class));
    }

    @OnClick(R.id.messageLayout)
    public void gotoMessage() {
        if (LoginInstance.isLogin()) {
            TrackUtil.trackScreenName("/user/inbox");
            MessageListActivity.startActivityForResult(getActivity());
        } else {
            LoginProxy.getInstance().gotoUserEnter(getActivity());
        }
    }

    @OnClick(R.id.role_layout)
    public void showChangeUserRoleDialog() {
        if (NetworkUtil.getConnectState(AppCoreRuntime.context) == NetworkUtil.CONNECT_NONE) {
            ToastUtil.toast(R.string.feedback_no_internet_1);
            return;
        }
        ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
        choiceDialog.setDialogTitle(getResources().getString(R.string.chat_msg_role_operation_change));
        choiceDialog.setDialogMessageVisibility(false);
        choiceDialog.setDialogCoupleStyleSetting(
                getResources().getString(R.string.operation_yes),
                getResources().getString(R.string.operation_no), new ChoiceDialog.DialogStyleCoupleCallback() {
                    @Override
                    public boolean onPositiveButtonClick() {
                        changeUserRole();
                        return false;
                    }

                    @Override
                    public boolean onNegativeButtonClick() {
                        return false;
                    }
                });
        showDialogFragment(choiceDialog);
    }

    public void changeUserRole() {
        final CtUserInfo info = LoginInstance.getInstance().getUserInfo();
        final int type = info.isTravel() ? CtUserInfo.USER_FINDER : CtUserInfo.USER_TRAVEL;
        showLoading();
        UserBusiness.changeType(apiProxy, type);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (LoginInstance.isLogin()) {
            refreshView();
        }
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        final CtUserInfo info = LoginInstance.getInstance().getUserInfo();
        String title;
        if (!LoginInstance.isLogin()) {
            title = ResourceUtil.getString(R.string.main_nav_me);
        } else if (info.isTravel()) {
            title = ResourceUtil.getString(R.string.user_role_traveller);
        } else {
            title = ResourceUtil.getString(R.string.user_role_insider);
        }
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarMiddleAreaName = title;
        customUiConfig.mTopbarStyle = CustomUiConfig.BarStyle.WHITE_STYLE;
        return customUiConfig;
    }
}
